package com.sangmo.boot.auth.core.handlers;

import com.sangmo.boot.auth.core.errors.ErrorMessages;
import com.sangmo.boot.auth.core.ClientService;
import com.sangmo.boot.auth.core.model.Client;
import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuthorizeHelper {
    @Autowired
    protected ClientService clientService;

    protected Client validateClientGrant(String clientId, String secret, String grantType, String resource, String scope) {
        Client client = this.validateClientAccess(clientId, resource, scope);

        if(!client.getSecret().equals(secret)) {
            throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_SECRET_WRONG);
        }
        if(!client.containsGrantType(grantType)) {
            throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_GRANTTYPE_WRONG);
        }
        return client;
    }

    protected Client validateClientAccess(String clientId, String resource, String scope) {
        Client client = clientService.find(clientId);
        if(client == null) {
            throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_NAMENOTEXISTS);
        }
        if (!Client.States.ENABLED.equals(client.getState())) {
            throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_DISABLED);
        }
        if(!client.containsResource(resource)) {
            throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_RESOURCE_WRONG);
        }
        if (!client.containsScope(scope)) {
            throw new ServiceException(StandardErrors.AUTHORIZED_WRONG.getStatus(), ErrorMessages.AUTH_CLIENT_SCOPE_WRONG, scope);
        }
        return client;
    }
}
